import re
import logging


def change_unixtime_now(m):
    logging.debug("匹配到了 「 {}({}()) {} 」".format(m.group(1), m.group(2), m.group(3)))
    new_date_format = "floor(extract(epoch FROM now()))*1000 as "
    return new_date_format


def change_from_unixtime_to_seconds(m):
    logging.debug("匹配到了 「 {}({} / 1000,'%Y-%m-%d %H:%i:%s') 」".format(m.group(1), m.group(2)))
    new_date_format = "to_char(to_timestamp({} / 1000),'yyyy-mm-dd hh24:mi:ss')".format(m.group(2))
    return new_date_format


def change_from_unixtime_to_day_hyphen(m):
    logging.info("change_unixtime_2_date_2")
    logging.debug("匹配到了 「 {}({} / 1000,'%Y-%m-%d') 」".format(m.group(1), m.group(2)))
    new_date_format = "to_char(to_timestamp({} / 1000),'yyyy-mm-dd')".format(m.group(2))
    return new_date_format


def rep_complex_fn_from_unixtime(document_content):
    logging.info(" 》》》 开始执行 from_unixtime 替换  >>>> ")

    # from_unixtime(now()) as
    unix_timestamp_patten = re.compile(r'(FROM_UNIXTIME|from_unixtime)\((NOW|now)\(\)\)\ (AS|as)')
    result = unix_timestamp_patten.sub(change_unixtime_now, document_content)
    document_content = result

    # -- 格式化到秒级别
    # from_unixtime\(vdl\.end_time \/ 1000\, \'\%Y\-\%m\-\%d \%H\:\%i\:\%s\'\)
    unix_timestamp_patten = re.compile(r'(FROM_UNIXTIME|from_unixtime)\((.*)\/1000\,\'\%Y\-\%m\-\%d \%H\:\%i\:\%s\'\)')
    result = unix_timestamp_patten.sub(change_from_unixtime_to_seconds, document_content)
    document_content = result

    # from_unixtime(ro.rtn_date/1000,'%Y-%m-%d')
    unix_timestamp_patten = re.compile(r'(FROM_UNIXTIME|from_unixtime)\((.*)\/1000\,\'\%Y\-\%m\-\%d\'\)')
    result = unix_timestamp_patten.sub(change_from_unixtime_to_day_hyphen, document_content)
    document_content = result

    return document_content
